# coding=utf-8
##
## Author: jmdvirus@aliyun.com
##
## Create: 2019年02月18日 星期一 11时42分34秒
##

import numpy as np
import cv2
import matplotlib.pyplot as plt
from sklearn import decomposition

mean = [20, 20]

def load_data():
    cov = [[5, 0,], [25, 25]]
    x, y = np.random.multivariate_normal(mean, cov, 1000).T
    #print("x = ", x, " , y = ", y)
    return (x, y)

def show(x, y):
    plt.plot(x, y, 'o', zorder=1)
    plt.axis([0, 40, 0, 40])
    plt.xlabel('feature 1')
    plt.ylabel('feature 2')

def pca_do(x, y):
    X = np.vstack((x, y)).T
    print("X = ", X)

    mu, eig = cv2.PCACompute(X, np.array([]))
    print("mu = ", mu, ", eig= ", eig)

    plt.plot(x, y, 'o', zorder=1)
    plt.quiver(mean[0], mean[1], eig[:, 0], eig[:, 1], zorder=3, 
            scale=0.2, units='xy')

    plt.text(mean[0] + 5 * eig[0, 0], mean[1] + 5 * eig[0, 1],
            'u1', zorder=5, fontsize = 16, bbox = dict(facecolor='white', alpha=0.6))
    plt.text(mean[0] + 7 * eig[1, 0], mean[1] + 4 * eig[1, 1],
            'u2', zorder=5, fontsize=16, bbox=dict(facecolor='white', alpha=0.6))
    plt.axis([0, 40, 0, 40])
    plt.xlabel('feature 1')
    plt.ylabel('feature 2')

def pca_do2(x, y):
    X = np.vstack((x, y)).T
    mu, eig = cv2.PCACompute(X, np.array([]))
    X2 = cv2.PCAProject(X, mu, eig)
    print("X2 = ", X2)
    plt.plot(X2[:, 0], X2[:, 1], 'o')
    plt.xlabel('first principal component')
    plt.ylabel('second principal component')
    plt.axis([-20, 20, -10, 10])

def ica_do(x, y):
    X = np.vstack((x, y)).T
    ica = decomposition.FastICA()
    X2 = ica.fit_transform(X)
    print("X2: ", X2)
    plt.plot(X2[:, 0], X2[:, 1], 'o')
    plt.xlabel('first independent component')
    plt.ylabel('second independent component')
    plt.axis([-0.2, 0.2, -0.2, 0.2])

def nmf_do(x, y):
    nmf = decomposition.NMF()
    X = np.vstack((x, y)).T
    X2 = nmf.fit_transform(X)
    print("X2: ", X2)
    plt.plot(X2[:, 0], X2[:, 1], 'o')
    plt.xlabel('first non-negative component')
    plt.ylabel('second non-negative component')
    plt.axis([-5, 15, -5, 15])

if __name__ == "__main__":
    x, y = load_data()
    #show(x, y)
    #pca_do(x, y)
    #pca_do2(x, y)
    #ica_do(x, y)
    nmf_do(x, y)

    plt.show()

